package com.hellobike.haxing.modules.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.util.DateUtils;
import com.hellobike.haxing.common.util.OrderUtils;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.hello.HelloDataExchange;
import com.hellobike.haxing.modules.hello.response.SettltQueryResponse;
import com.hellobike.haxing.modules.hello.response.SettltResponse;
import com.hellobike.haxing.modules.shop.constant.ShopConstants;
import com.hellobike.haxing.modules.shop.entity.Shop;
import com.hellobike.haxing.modules.shop.entity.ShopWithdrew;
import com.hellobike.haxing.modules.shop.mapper.ShopWithdrewMapper;
import com.hellobike.haxing.modules.shop.service.IShopAccountService;
import com.hellobike.haxing.modules.shop.service.IShopService;
import com.hellobike.haxing.modules.shop.service.IShopWithdrewMonthCountService;
import com.hellobike.haxing.modules.shop.service.IShopWithdrewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @Description: 提现申请
 * @Author: haxing-boot
 * @Date: 2020-02-08
 * @Version: V1.0L
 */
@Slf4j
@Service
public class ShopWithdrewServiceImpl extends ServiceImpl<ShopWithdrewMapper, ShopWithdrew> implements IShopWithdrewService {
    @Autowired
    private ShopWithdrewMapper shopWithdrewMapper;
    @Autowired
    private IShopAccountService shopAccountService;
    @Autowired
    private IShopWithdrewMonthCountService shopWithdrewMonthCountService;
    @Autowired
    private IShopService shopService;
    @Autowired
    private OrderUtils orderUtils;
    @Autowired
    private HelloDataExchange helloDataExchange;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> approveBatch(List<Long> ids, String auditUser) {
        for (Long id : ids) {
            this.approve(id, auditUser);
        }
        return Result.ok("批量审核通过成功,请查看打款结果");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> approve(Long id, String auditUser) {
        ShopWithdrew shopWithdrew = super.getById(id);
        if (!ShopConstants.WITHDREW_STATUS_7.equals(shopWithdrew.getStatus())) {
            return Result.error("数据状态不正确");
        }
        String guid = shopWithdrewMapper.getUserGuid(shopWithdrew.getShopId());
        log.info("=审核通过获取guid={}==",guid);
//        if(StringUtils.isEmpty(guid)){
//            return Result.error("用户guid不存在");
//        }
//        try{
//            shopWithdrew = getLoanResult(shopWithdrew,guid);
//        }catch (Exception e){
//            return Result.error("打款接口调用内部打款系统异常,异常信息:"+e.getMessage());
//        }
        shopWithdrew.setAuditTime(DateUtils.getDate());
        shopWithdrew.setAuditUser(auditUser);
        shopWithdrew.setLoanTime(DateUtils.getDate());
        shopWithdrew.setLoanUser(auditUser);
        shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_2);
        super.updateById(shopWithdrew);
        shopWithdrewMonthCountService.saveMonthAmount(shopWithdrew.getShopId(), shopWithdrew.getAmount());
        if (ShopConstants.WITHDREW_STATUS_4.equals(shopWithdrew.getStatus())) {
            shopAccountService.updateWithSuccessSubStatus(shopWithdrew.getId());
            log.info("=审核通过打款成功时更新账单状态=applyId={}==", shopWithdrew.getId());
        }
        return Result.ok("审核通过成功,请查看打款结果");
    }

    /**
     * 获取打款结果
     *
     * @return
     */
    private ShopWithdrew getLoanResult(ShopWithdrew shopWithdrew, String guid) {
        log.info("==请求打款接口参数=guid={}=卡号={}=实际金额={}=业务编码ID={}==", guid, shopWithdrew.getBankCardNo(), shopWithdrew.getActualAmount(), shopWithdrew.getId());
//        String businessNo=orderUtils.getShopWithdrewBillNo(shopWithdrew.getShopId());
        SettltResponse settltResponse = helloDataExchange.settle(guid, shopWithdrew.getBankCardNo(), shopWithdrew.getActualAmount(), shopWithdrew.getId().toString());
        log.info("=提现=SettltResponse=相应结果={}=", JSON.toJSONString(settltResponse));
        if (settltResponse.getCode() >= 0) {
            String reason = settltResponse.getData().getReason();
            if (!StringUtils.isEmpty(reason) && reason.length() > 10) {
                reason = reason.substring(0, 10);
            }
            shopWithdrew.setLoanFailReason(reason);
            /**
             *  结算结果 (1, "处理中")
             *  (2, "成功")
             *  (3, "失败");
             */
            Integer result = settltResponse.getData().getSettleResult();
            if (result != null && 1 == result) {
                shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_6);
            } else if (result != null && 2 == result) {
                shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_4);
            } else if (result != null && 3 == result) {
                shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_5);
            } else {
                shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_5);
            }
        } else {
            shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_5);
            String msg = settltResponse.getMsg();
            if (!StringUtils.isEmpty(msg) && msg.length() > 10) {
                msg = msg.substring(0, 10);
            }
            shopWithdrew.setLoanFailReason(msg);
        }
//        shopWithdrew.setBusinessNo(businessNo);
        return shopWithdrew;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> reject(ShopWithdrew shopWithdrew) throws Exception {
        ShopWithdrew withdrew = super.getById(shopWithdrew.getId());
        if (!ShopConstants.WITHDREW_STATUS_7.equals(shopWithdrew.getStatus())
                && !ShopConstants.WITHDREW_STATUS_1.equals(shopWithdrew.getStatus())) {
            return Result.error("数据状态不正确");
        }
        shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_3);
        shopWithdrew.setAuditTime(DateUtils.getDate());
        super.updateById(shopWithdrew);
        shopAccountService.addIncome(withdrew.getShopId(), withdrew.getAmount(), ShopConstants.ACCOUNT_STATUS_3, shopWithdrew.getReason());
        shopAccountService.updateRejectSubStatus(shopWithdrew.getId());
        return Result.ok("审核拒绝成功!");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void loanBatch(List<Long> ids, String loanUser) {
        shopWithdrewMapper.loanBatch(ids, loanUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> loan(Long id, String loanUser) {
        ShopWithdrew shopWithdrew = super.getById(id);
        if (!ShopConstants.WITHDREW_STATUS_5.equals(shopWithdrew.getStatus())) {
            return Result.error("数据状态不正确");
        }
        String guid = shopWithdrewMapper.getUserGuid(shopWithdrew.getShopId());
        log.info("=再次打款获取guid={}==", guid);
        if (StringUtils.isEmpty(guid)) {
            return Result.error("用户guid不存在");
        }
        try {
            shopWithdrew = getLoanResult(shopWithdrew, guid);
        } catch (Exception e) {
            return Result.error("打款接口调用内部打款系统异常,异常信息:" + e.getMessage());
        }
        shopWithdrew.setLoanTime(DateUtils.getDate());
        shopWithdrew.setLoanUser(loanUser);
        super.updateById(shopWithdrew);
        if (ShopConstants.WITHDREW_STATUS_4.equals(shopWithdrew.getStatus())) {
            shopAccountService.updateWithSuccessSubStatus(shopWithdrew.getId());
            log.info("=再次打款成功时更新账单状态=applyId={}==", shopWithdrew.getId());
        }
        return Result.ok("打款操作成功，请查看打款结果!");
    }

    @Override
    public void delete(Long id, Integer userId) {
        shopWithdrewMapper.deleteWithdrew(id, userId);
    }

    @Override
    public void deleteBatch(List<Long> ids, Integer userId) {
        shopWithdrewMapper.deleteBatch(ids, userId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void yyapproveBatch(List<Long> ids, String auditUser) {
        shopWithdrewMapper.yyapproveBatch(ids, auditUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void yyapprove(Long id, String auditUser) {
        ShopWithdrew shopWithdrew = new ShopWithdrew();
        shopWithdrew.setYyauditTime(DateUtils.getDate());
        shopWithdrew.setYyauditUser(auditUser);
        shopWithdrew.setId(id);
        shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_7);
        super.updateById(shopWithdrew);
    }

    @Override
    public IPage<ShopWithdrew> queryYyPage(ShopWithdrew shopWithdrew, Page<ShopWithdrew> page, Map<String, String[]> parameterMap) {
        QueryWrapper<ShopWithdrew> queryWrapper = QueryGenerator.initQueryWrapper(shopWithdrew, parameterMap);
        IPage<ShopWithdrew> result = super.page(page, queryWrapper);
        for (ShopWithdrew withdrew : result.getRecords()) {
            Shop shop = shopService.getById(withdrew.getShopId());
            if (shop.getTotalAmount().compareTo(BigDecimal.ZERO) < 0) {
                withdrew.setStatus(ShopConstants.WITHDREW_STATUS_8);
            }
            withdrew.setTotalAmount(shop.getTotalAmount());
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSettleQuery() {
        log.info("=提现中获取结果开始时间={}=", DateUtils.getDate());
        QueryWrapper<ShopWithdrew> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ShopWithdrew::getStatus, ShopConstants.WITHDREW_STATUS_6);
        List<ShopWithdrew> list = super.baseMapper.selectList(queryWrapper);
        for (ShopWithdrew shopWithdrew : list) {
            if (ShopConstants.WITHDREW_STATUS_5.equals(shopWithdrew.getStatus())) {
                continue;
            }
            String guid = shopWithdrewMapper.getUserGuid(shopWithdrew.getShopId());
            log.info("=定时获取打款结果参数guid={}=业务编码ID={}=", guid, shopWithdrew.getId());
            if (StringUtils.isEmpty(guid)) {
                continue;
            }

            SettltQueryResponse settltResponse = helloDataExchange.settleQuery(guid, shopWithdrew.getId().toString());
            log.info("=定时获取打款结果SettltResponse响应={}==", JSON.toJSONString(settltResponse));
            if (settltResponse.getCode() < 0) {
                continue;
            }
//            shopWithdrew.setInnerTradeNo(settltResponse.getData().getInnerTradeNo());
//            String reason = settltResponse.getData().getReason();
//            if(!StringUtils.isEmpty(reason) && reason.length()>10){
//                reason=reason.substring(0,10);
//            }
//            shopWithdrew.setLoanFailReason(reason);
            Integer result = settltResponse.getData().getResult();
            if (result == null || 1 == result) {
                continue;
            } else if (result != null && 2 == result) {
                shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_4);
            } else if (result != null && 3 == result) {
                shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_5);
            }
            shopWithdrew.setLoanTime(DateUtils.getDate());
            super.updateById(shopWithdrew);
            if (ShopConstants.WITHDREW_STATUS_4.equals(shopWithdrew.getStatus())) {
                shopAccountService.updateWithSuccessSubStatus(shopWithdrew.getId());
                log.info("=定时获取结果为打款成功时更新账单状态=applyId={}==", shopWithdrew.getId());
            }
        }
    }

    @Override
    public Result yyreject(ShopWithdrew shopWithdrew, Long id, String username) {
        ShopWithdrew withdrew = super.getById(id);
        if (!ShopConstants.WITHDREW_STATUS_1.equals(shopWithdrew.getStatus())) {
            return Result.error("数据状态不正确");
        }
        shopWithdrew.setStatus(ShopConstants.WITHDREW_STATUS_3);
        shopWithdrew.setAuditTime(DateUtils.getDate());
        super.updateById(shopWithdrew);
        shopAccountService.addIncome(withdrew.getShopId(), withdrew.getAmount(), ShopConstants.ACCOUNT_STATUS_3, shopWithdrew.getReason());
        shopAccountService.updateRejectSubStatus(shopWithdrew.getId());
        return Result.ok("审核拒绝成功!");
    }

}
